package com.heba.greenmulu.diary;

import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;

import com.heba.config.CommonConfig;
import com.heba.event.MessageEvent;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.utils.ToastShow;

import org.greenrobot.eventbus.EventBus;

import cn.bingoogolapple.qrcode.core.BarcodeType;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zbar.ZBarView;

/**
 * 掃描產品
 * Created by jason on 2020/3/2.
 */
public class ItemDiaryScanProductActivity extends BaseActivity implements QRCodeView.Delegate {

    private ZBarView mZBarView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diary_scan_product);
        initTopbar();
        findViewById();
        initView();
    }

    @Override
    protected void findViewById() {
        mZBarView = findViewById(R.id.zbarview);
    }

    @Override
    protected void initView() {
        txt_title.setText(getResources().getString(R.string.diary_scan_product));

        mZBarView.setDelegate(this);
        mZBarView.setType(BarcodeType.ONE_DIMENSION, null);
        mZBarView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
//        mZBarView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别
        mZBarView.startSpotAndShowRect(); // 显示扫描框，并开始识别
    }

    @Override
    public void onStart() {
        super.onStart();
        mZBarView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
//        mZBarView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别
        mZBarView.startSpotAndShowRect(); // 显示扫描框，并开始识别
    }

    @Override
    public void onStop() {
        super.onStop();
        mZBarView.stopCamera(); // 关闭摄像头预览，并且隐藏扫描框
    }

    /**
     * 震动
     */
    private void vibrate() {
        Vibrator vibrator = (Vibrator) this.getSystemService(this.VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        /**
         * 掃描成功處理
         */
        Log.i("onScanQRCodeSuccess", "result:" + result);

        //震动
        vibrate();

        MessageEvent event = new MessageEvent();
        event.setEvent(CommonConfig.SCAN_PRODUCT_CODE);
        event.setProductCode(result);
        EventBus.getDefault().post(event);
        finishActivity();
    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {

    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        Log.e("OpenCameraError", "打开相机出错");
        ToastShow.displayToast(this, getResources().getString(R.string.camera_failure));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mZBarView.onDestroy();  // 销毁二维码扫描控件
    }
}
